﻿Imports Negocio
Imports Servicios
Imports Excepciones

Public Class frmABMPermiso

    Private _perfil As New Perfil()
    Private _modulos As New List(Of Modulo)
    Protected Overrides Sub PreLoad()
        Me.Icon = Icon.FromHandle(Global.SIPRO.My.Resources.Resources.lock.GetHicon())
    End Sub
    Sub New()
        InitializeComponent()
    End Sub

    Sub New(perfil As Perfil)
        Me.New()
        _perfil = perfil
    End Sub

    Private Sub frmABMPermiso_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim images As New ImageList()
        images.Images.Add(Global.SIPRO.My.Resources.home)
        images.Images.Add(Global.SIPRO.My.Resources.star)
        tvPermisos.ImageList = images
        Try
            _modulos = GesPermisos.LoadPermisos(_perfil)
        Catch ex As Exception
            My.Application.HandlerException(ex)
            Me.Close()
        End Try
        loadTree()
    End Sub

    Private Sub loadTree()
        For Each modu As Modulo In _modulos
            Dim node As New TreeNode(modu.Nombre)
            node.Checked = Convert.ToBoolean(modu.Permitido)
            node.ImageIndex = 0
            node.SelectedImageIndex = 0
            node.Tag = modu
            For Each acc As ModuloAccion In modu.ModulosAccion
                Dim nodeAcc As New TreeNode(acc.Accion)
                nodeAcc.ImageIndex = 1
                nodeAcc.SelectedImageIndex = 1
                nodeAcc.Checked = Convert.ToBoolean(acc.Permitido)
                nodeAcc.Tag = acc
                node.Nodes.Add(nodeAcc)
            Next
            tvPermisos.Nodes.Add(node)
        Next
    End Sub

    Private Sub btnGuardar_Click(sender As System.Object, e As System.EventArgs) Handles btnGuardar.Click

        Try
            For Each node As TreeNode In tvPermisos.Nodes
                DirectCast(node.Tag, Modulo).Permitido = node.Checked
                For Each nodeacc In node.Nodes
                    DirectCast(nodeacc.Tag, ModuloAccion).Permitido = nodeacc.Checked
                Next
            Next
        Catch ex As Exception
            My.Application.HandlerException(New PermisoSaveException())
        End Try
        Try
            GesPermisos.Guardar(_perfil, _modulos)
        Catch ex As Exception
            My.Application.HandlerException(ex)
        End Try

        Me.Close()
    End Sub

    Private Sub btnCancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub
End Class